<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>scrollInto实现目录框</title>
	</head>
	<style>
		html,body{
			width: 100%;
			height: 100%;
		}
		.mody{
			width: 100%;
			height: 100%;
		}
		.content{
			width: 100%;
			height: 100%;
			background-color: aqua;
			margin-top: 20px;
		}
		.mulu{
			width: 200px;
			min-height: 30px;
			position: fixed;
			top: 4px;
			right: 2px;
			background-color: beige;
			padding: 2px 10px;
		}
		.mulu a{
			display: block;
			margin-top: 10px;
		}
		.selected{
			background-color: aqua;
		}
	</style>
	<body>
		<div class="mody">
			<div class="item1 content" id="app1">
				第一章内容
			</div>
			<div class="item2 content" id="app2">
				第二章内容
			</div>
			<div class="item3 content" id="app3">
				第三章内容
			</div>
		</div>
		<div class="mulu">
			<a class="item" id="item1">第一章</a>
			<a class="item" id="item2">第二章</a>
			<a class="item" id="item3">第三章</a>
		</div>
		<script>
			 let Item=document.querySelectorAll(".item")
			 let contents=document.querySelectorAll(".content");
			 
			 Item.forEach((node,index)=>{
			     node.addEventListener('click', function(event) {
			         // 阻止默认行为，比如页面跳转
			         event.preventDefault();
					 var targetElement = contents[index];
					 targetElement.scrollIntoView({ behavior: 'smooth', block: 'center' })
				})
			});
			
			contents.forEach((node,index)=>{
					window.addEventListener('scroll', function() {
					    // 获取第二章内容元素相对于视口的位置信息
					    let domRect = node.getBoundingClientRect();
					
					    // 判断第二章是否在可视区域内
					    if (domRect.top >= 0 && domRect.bottom <= window.innerHeight) {
							 var targetElement = Item[index];
							 Item.forEach((item) => {
							       item.classList.remove('selected');
							 });
							 targetElement.classList.add("selected");
					    }
					});
			});
		</script>
	</body>
</html>